from pathlib import Path

import aiofiles

from genius.type import Track
import eyed3

from utils import download_image


async def set_track(path: Path, track: Track):
    audiofile = eyed3.load(path)

    if track.album is not None:
        audiofile.tag.album = track.album.title
        audiofile.tag.album_artist = track.album.artist

    audiofile.tag.artist = track.artist
    audiofile.tag.title = track.title
    audiofile.tag.track_num = track.number
    audiofile.tag.lyrics.set(track.lyrics)

    if track.cover:
        cover = await download_image(track.cover)
        async with aiofiles.open(cover, "rb") as f:
            content = await f.read()
        audiofile.tag.images.set(3, content, "image/jpeg", u"")

    audiofile.tag.save()
